package app.musicPlayer.domain;
 
import java.io.IOException;
import java.util.ArrayList;

import com.facebook.android.FacebookError;
import com.facebook.android.R;

import app.socialInteraction.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import app.persistencia.CancionLista;
import app.persistencia.ListaDeReproduccion;
import app.persistencia.ListasDeReproduccion;
import app.utils.Utiles;
import de.vdheide.mp3.*;

 
public class Mp3player extends Activity {
 
    final private MediaPlayer mediaPlayer = new MediaPlayer();
    private SeekBar seekBar;
    private CancionLista cl;
    private final Handler handler = new Handler();
    private String durtotal;
 

    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            System.out.println("Create");
    }
    @Override
    public void onStart() {
    		super.onStart();
    	       System.out.println(ReproduccionActual.getIntances().getEnReproduccion().size());
               System.out.println("Start");

            setContentView(R.layout.player);
            try {
				initViews();
			} catch (ID3v2WrongCRCException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ID3v2DecompressionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ID3v2IllegalVersionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoMP3FrameException e) {
			 	// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FrameDamagedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

 
    }
    
    private String escriuMin(int x) {
    	String res = new String();
    	int min, seg;
    	min = x/60;
    	seg = x%60;
    	if (min < 10) res += 0+"";
    	res+= min+":";
    	if (seg < 10) res+=0+"";
    	res+= seg+"";
    	return res;
    }
 
    private void initViews() throws ID3v2WrongCRCException, ID3v2DecompressionException, ID3v2IllegalVersionException, IOException, NoMP3FrameException, FrameDamagedException, InterruptedException  {
    	
    	Button mPlayButton;
        Button mPauseButton;
        Button mSkipButton;
        Button mRewindButton;
        Button mStopButton;
        ImageView facebook;
        ImageView tweetButton;


        /*MP3File mp = new MP3File(path);
    	TagContent tc = new TagContent();
    	tc = mp.getPicture();
    	byte[] image = tc.getBinaryContent();
    	Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
    	imageView.setImageBitmap(bmp);*/
    	
        
        mPlayButton = (Button) findViewById(R.id.play);
        mPauseButton = (Button) findViewById(R.id.pause);
        mSkipButton = (Button) findViewById(R.id.fwd);
        mRewindButton = (Button) findViewById(R.id.rew);
        mStopButton = (Button) findViewById(R.id.stop);
        facebook = (ImageView) findViewById(R.id.FacebookButton);
        tweetButton = (ImageView) findViewById(R.id.tweetButton);


        mPlayButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {try {
			buttonClickplay();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}});
        mPauseButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {buttonClickpause();}});
        mStopButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {buttonClickstop();}});
        mSkipButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {try {
			buttonClikSkip();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}});
        mRewindButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {try {
			buttonClikRewind();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}});
       

       //mediaPlayer = new MediaPlayer();
       cl = ReproduccionActual.getIntances().getNextSong();
       System.out.println(ReproduccionActual.getIntances().getEnReproduccion().size());
       String path = cl.getPath();
       mediaPlayer.reset(); 
       mediaPlayer.setDataSource(path);
       mediaPlayer.prepare();

       
       TextView textView = (TextView) findViewById(R.id.textView1);
       textView.setText(cl.getTittle());
       
       TextView textView2 = (TextView) findViewById(R.id.textView2);
       textView2.setText(cl.getArtist());
       
       TextView textView3 = (TextView) findViewById(R.id.textView3);
       textView3.setText(cl.getAlbum());
       
       int durt = mediaPlayer.getDuration() /1000;
       durtotal = escriuMin(durt);
       
       int dura = mediaPlayer.getCurrentPosition() /1000;
       String dur = escriuMin(dura);
       TextView textView4 = (TextView) findViewById(R.id.textView4);
       textView4.setText(dur+"                                                           "+durtotal);
       facebook.setOnClickListener(new OnClickListener() {
    	   public void onClick(View v) {
    		   updateFacebookStatus(cl.getTittle(), cl.getAlbum(), cl.getArtist());
	   }});
       /**
        * TWITTER
        * 
        */
       tweetButton.setOnClickListener(new OnClickListener() {
    	   public void onClick(View v) {
    		   Tweet.enviaTweet();
	   }});

       
       
        seekBar = (SeekBar) findViewById(R.id.SeekBar01);
        seekBar.setMax(mediaPlayer.getDuration());
        seekBar.setOnTouchListener(new OnTouchListener() {public boolean onTouch(View v, MotionEvent event) {
        	seekChange(v);
			return false; }
		});
        
        Thread.sleep (1000);
        buttonClickplay();
 
    }
    
    private void buttonClikSkip() throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
    	
        cl = ReproduccionActual.getIntances().getNextSong();
    	if (cl != null) {
    		mediaPlayer.pause();
    		String path = cl.getPath();
	    	mediaPlayer.reset();
	    	mediaPlayer.setDataSource(path);
	    	mediaPlayer.prepare();
	        seekBar = (SeekBar) findViewById(R.id.SeekBar01);
	        seekBar.setMax(mediaPlayer.getDuration());
	        seekBar.setOnTouchListener(new OnTouchListener() {public boolean onTouch(View v, MotionEvent event) {
	        	seekChange(v);
				return false; }
			});
	        TextView textView = (TextView) findViewById(R.id.textView1);
	        textView.setText(cl.getTittle());     
	        TextView textView2 = (TextView) findViewById(R.id.textView2);
	        textView2.setText(cl.getArtist());
	        TextView textView3 = (TextView) findViewById(R.id.textView3);
	        textView3.setText(cl.getAlbum());
	        int durt = mediaPlayer.getDuration() /1000;
	        durtotal = escriuMin(durt);
	        int dura = mediaPlayer.getCurrentPosition() /1000;
	        String dur = escriuMin(dura);
	        TextView textView4 = (TextView) findViewById(R.id.textView4);
	        textView4.setText(dur+"                                                           "+durtotal);
	        Thread.sleep (1000);
	        buttonClickplay();
    	} else {
    		buttonClickstop();
    		Toast toast1 = Toast.makeText(getApplicationContext(), "No hi ha m�s can�ons per a reproduir", Toast.LENGTH_SHORT);
    	    toast1.show();
    	}
    }
    
    private void buttonClikRewind() throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
    	cl = ReproduccionActual.getIntances().getPreviousSong();
        System.out.println("arriba");
    	if (cl != null) {
    		mediaPlayer.pause();
    		String path = cl.getPath();
	    	mediaPlayer.reset();
	    	mediaPlayer.setDataSource(path);
	    	mediaPlayer.prepare();
	        seekBar = (SeekBar) findViewById(R.id.SeekBar01);
	        seekBar.setMax(mediaPlayer.getDuration());
	        seekBar.setOnTouchListener(new OnTouchListener() {public boolean onTouch(View v, MotionEvent event) {
	        	seekChange(v);
				return false; }
			});
	        TextView textView = (TextView) findViewById(R.id.textView1);
	        textView.setText(cl.getTittle());     
	        TextView textView2 = (TextView) findViewById(R.id.textView2);
	        textView2.setText(cl.getArtist());
	        TextView textView3 = (TextView) findViewById(R.id.textView3);
	        textView3.setText(cl.getAlbum());
	        int durt = mediaPlayer.getDuration() /1000;
	        durtotal = escriuMin(durt);
	        int dura = mediaPlayer.getCurrentPosition() /1000;
	        String dur = escriuMin(dura);
	        TextView textView4 = (TextView) findViewById(R.id.textView4);
	        textView4.setText(dur+"                                                           "+durtotal);
	        
	        Thread.sleep (1000);
	        buttonClickplay();


	        
    	} else {
    		buttonClickstop();
    		Toast toast1 = Toast.makeText(getApplicationContext(), "�s la primera can��", Toast.LENGTH_SHORT);
    	    toast1.show();
    	}
    }
    
    public void startPlayProgressUpdater() throws IllegalArgumentException, IllegalStateException, IOException, InterruptedException {
    	seekBar.setProgress(mediaPlayer.getCurrentPosition());
    	int dura = mediaPlayer.getCurrentPosition() /1000;
	    if (mediaPlayer.getCurrentPosition() >= mediaPlayer.getDuration()-100) {
	    	buttonClikSkip();
	    }
	    else {
	        String dur = escriuMin(dura);
	        TextView textView4 = (TextView) findViewById(R.id.textView4);
	        textView4.setText(dur+"                                                           "+durtotal);
			if (mediaPlayer.isPlaying()) {
				Runnable notification = new Runnable() {
			        public void run() {
			        	try {
							startPlayProgressUpdater();
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			        	
					}
			    };
			    handler.postDelayed(notification,1000);
	    	}
	    }
    } 
 

    private void seekChange(View v){
    	if(mediaPlayer.isPlaying()){
	    	SeekBar sb = (SeekBar)v;
			mediaPlayer.seekTo(sb.getProgress());
		}
    }
 

    private void buttonClickplay() throws IllegalArgumentException, IOException, InterruptedException{
        try{
        	mediaPlayer.start();
        	//updateFacebookStatus("Esto es una prueba muy real");
            startPlayProgressUpdater();
            Toast toast1 = Toast.makeText(getApplicationContext(), "En reproducci�", Toast.LENGTH_SHORT);
    	    toast1.show();

        }catch (IllegalStateException e) {
        	mediaPlayer.pause();
        }
    }
    
    private void buttonClickstop(){
    	SeekBar sb = (SeekBar)findViewById(R.id.SeekBar01);
    	sb.setProgress(0);
    	mediaPlayer.seekTo(0);
        mediaPlayer.pause();
        //Toast toast1 = Toast.makeText(getApplicationContext(), "Stop", Toast.LENGTH_SHORT);
	    //toast1.show();
    }
    
    private void buttonClickpause(){
    	try{
	    	mediaPlayer.pause();
	        System.out.println("pause");
    		Toast toast1 = Toast.makeText(getApplicationContext(), "Can�� pausada", Toast.LENGTH_SHORT);
    	    toast1.show();
    	}catch (IllegalStateException e){
    		mediaPlayer.pause();
    	}
    } 
    
    

	public boolean onCreateOptionsMenu(Menu menu) {

	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menurep, menu);
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.MnuOpc1:
	        	returnToViewMain(null);
	            return true;
	        case R.id.MnuOpc2:
	        	canvillista();
	        	return true;
	       default :
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private void returnToViewMain(Object object) {
		Bundle b = new Bundle();
    	b.putString(Utiles.FACTORDESELECCION, String.valueOf(Utiles.NON_SELECT));
    	b.putString(Utiles.VALOR, " ");
		Intent myIntent = new Intent(Mp3player.this, SocialMusicPlayerActivity.class);
		if(b != null) {
    		myIntent.putExtras(b);
    	}
		//myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(myIntent);
	}
	
	private void canvillista() {
		final ArrayList<ListaDeReproduccion> li =
				ListasDeReproduccion.getIntances().getList();
		String[] items = new String[li.size()];
		for(int i= 0; i < li.size(); i++)
			items[i]=li.get(i).getName();
		  
		    AlertDialog.Builder builder = new AlertDialog.Builder(this);
		 
		    builder.setTitle("Reproducci�");
		    builder.setItems(items, new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int item) {
		    		int idListSelected = li.get(item).getId();
		    		if(ListasDeReproduccion.getIntances().getListaDeReproduccion(idListSelected).isEmpty()) {
		    			Toast toast1 = Toast.makeText(getApplicationContext(), "Lista de reproduccion vacia", Toast.LENGTH_SHORT);
		        	    toast1.show();
						return;
					}
					ReproduccionActual.getIntances().assignNewSongsList(
							ListasDeReproduccion.getIntances().
							getListaDeReproduccion(idListSelected).getListaRep());
							try {
								buttonClikSkip();
							} catch (IllegalArgumentException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IllegalStateException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
		        }

		    });
		    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	 	    	public void onClick(DialogInterface dialog, int which) {
	 	    		
	 	    	} 
	    	});
		    builder.show();
	}
	
	@Override
	public void onBackPressed()
    {
		returnToViewMain(null);
        return;
    }
	public void updateFacebookStatus(String tittle, String album, String Artist) {
	    /**
	     * TODO configurar mensaje
	     */
		String video = "";
		
		String message = "Estoy escuchando "+tittle;
		if(!album.isEmpty())
			message+= " del album "+album;
		if(!Artist.isEmpty())
			message+= " de "+Artist;
		message+=".";
		if(Utility.mFacebook.isSessionValid()) {
			Bundle params = new Bundle();
		    params.putString("caption", "Comparte con Social Music Player");
		    params.putString("description",message);
		    //params.putString("message", )
		    //params.putString("picture", Utility.HACK_ICON_URL);
		    params.putString("name", "SOCIAL MUSIC PLAYER");
		    /**Put a link*/
		    if(video.isEmpty())
			    params.putString("picture", Utility.HACK_ICON_URL);
		    else
		    	params.putString("link", "http://www.youtube.com/watch?v=TKNWAXRg3iA");
		    Utility.mFacebook.dialog(Mp3player.this, "feed", params, new UpdateStatusListener());
		    String access_token = Utility.mFacebook.getAccessToken();
		    System.out.println(access_token);
		}
		else 
			Utiles.showMessage(Mp3player.this, "No estas logueado en facebook");
	}
	public class UpdateStatusListener extends BaseDialogListener {
        
        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");
            if (postId != null) {
                Utiles.showMessage(Mp3player.this, "Publicado en Facebook");
            } else {
                Toast toast = Toast.makeText(getApplicationContext(), "No wall post made",
                        Toast.LENGTH_SHORT);
                toast.show();
            }
        }

        
        public void onFacebookError(FacebookError error) {
            Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

        
        public void onCancel() {
            Toast toast = Toast.makeText(getApplicationContext(), "Update status cancelled",
                    Toast.LENGTH_SHORT);
            toast.show();
        }
    }
}